package com.lcn.comm.framework.task;

import com.weibo.api.motan.util.LoggerUtil;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>类说明</p>
 *
 * @author 张峰 zfvip_it@163.com
 * @create: 下午4:27
 */
public class Task {

    /**
     * 互斥锁对象
     */
    private Lock lock = null;

    /**
     * 锁监视对象
     */
    private Condition condition = null;

    /**
     * 是否被唤醒
     */
    private volatile boolean isNotify = false;

    /**
     * 是否执行等待
     */
    private volatile boolean isAwait = false;

    /**
     * 事务组id
     */
    protected String groupId;

    /**
     * 唯一标示key
     */
    protected String requestId;

    /**
     * 数据状态用于业务处理
     */
    protected volatile int state = 0;

    /**
     * 回调对象
     */
    protected ICallBack callBack;

    public Task() {
        lock = new ReentrantLock();
        condition = lock.newCondition();
    }

    public boolean isNotify() {
        return isNotify;
    }

    public boolean isAwait() {
        return isAwait;
    }

    public String getGroupId() {
        return groupId;
    }

    public void setGroupId(String groupId) {
        this.groupId = groupId;
    }

    public String getRequestId() {
        return requestId;
    }

    public void setRequestId(String requestId) {
        this.requestId = requestId;
    }

    public int getState() {
        return state;
    }

    public void setState(int state) {
        this.state = state;
    }

    public void setCallBack(ICallBack callBack) {
        this.callBack = callBack;
    }

    public ICallBack getCallBack() {
        return callBack;
    }

    /**
     * 让当前线程处于等待
     */
    public void waitTask() {
        try {
            this.lock.lock();
            isAwait = true;
            condition.await();
        } catch (Throwable e) {
            LoggerUtil.info("线程名称" + Thread.currentThread().getName());
            e.printStackTrace();
        } finally {
            this.lock.unlock();
        }
    }

    /**
     * 唤醒当前线程
     */
    public void signalTask() {
        while (!isAwait() && !Thread.currentThread().interrupted()) {
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try {
            this.lock.lock();
            condition.signal();
            isNotify = true;
        } catch (Throwable e) {
        } finally {
            this.lock.unlock();
        }
    }

    /**
     * 清楚当前task
     */
    public void remove() {
        ConditionUtils.getInstance().removeTask(getRequestId());
    }

    /**
     * 是否已删除
     *
     * @return
     */
    public boolean isRemove() {
        return !ConditionUtils.getInstance().hasTask(getRequestId());
    }


}
